package com.mxf.code.repository;


import com.mxf.code.entity.node.EntityBaseNode;
import com.mxf.code.response.EntityDataDetailResponse;
import com.mxf.code.response.EntityDataPageResponse;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author mxf
 * @version 1.0
 * @description: 实体管理
 * @date 2023/5/10
 */
@Repository
public interface EntityManagerRepository extends Neo4jRepository<EntityBaseNode, Long> {

    @Query("MATCH (s:实体)-[r:`属于`]->(b:本体) " +
            "WHERE ($ontologyName IS NULL OR b.name CONTAINS $ontologyName) " +
            "AND ($entityName IS NULL OR s.name CONTAINS $entityName) " +
            "RETURN s,s.id as idNum,b.id as ontologyId,s.name as entityName,s.creator as creator," +
            "s.createDate as createDate,b.name as ontologyName ORDER BY s.createDate DESC SKIP $skip LIMIT $limit")
    List<EntityDataPageResponse> pageData(@Param("ontologyName") String ontologyName,
                                          @Param("entityName") String entityName,
                                          @Param("skip") int skip,
                                          @Param("limit") int limit);

    @Query("MATCH (s:实体)-[r:`属于`]->(b:本体) " +
            "WHERE ($ontologyName IS NULL OR b.name CONTAINS $ontologyName) " +
            "AND ($entityName IS NULL OR s.name CONTAINS $entityName) " +
            "RETURN count(*)")
    int totalPage(@Param("ontologyName") String ontologyName,
                  @Param("entityName") String entityName);

    @Query("MATCH (t:本体 {id:{ontologyId}}) " +
            "CREATE (p:实体 $entityProperties)-[:属于]->(t) ")
    void saveEntryData(@Param("ontologyId") Long ontologyId,
                       @Param("entityProperties") Map<String, Object> entityProperties);

    @Query("MATCH (p:实体) WHERE p.id = $id SET p += $entityProperties ")
    void modifyEntryData(@Param("id") Long id,
                         @Param("entityProperties") Map<String, Object> entityProperties);

    @Query("MATCH (p:实体)-[:属于]->(t:本体) " +
            "WHERE t.id=$ontologyId and p.id=$entityId " +
            "RETURN p.id as idNum,t.id as ontologyId, t.name as ontologyName, properties(p) as entityProperties")
    EntityDataDetailResponse getEntityById(@Param("ontologyId") Long ontologyId, @Param("entityId") Long entityId);

    @Query("MATCH (p:实体) " +
            "WHERE p.id = $id " +
            "DETACH DELETE p ")
    void delete(@Param("id") Long id);
}
